use strict;
use File::Spec;
use Zim::File;
use Zim::Page;
use Zim::Formats;
use Zim::Store::Files;

=head1 NAME

PrintToBrowser

=head1 VERSION

0.18

=head1 DESCRIPTION

Allows zim to "print" to the browser.
Inteded as temporary fix until real printing support is implemented.

=head1 AUTHOR

Jaap Karssenberg (Pardus) E<lt>pardus@cpan.orgE<gt>

Copyright (c) 2006 Jaap G Karssenberg. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

=cut

my $app  = Zim::GUI->current;

$app->{actions}->add_actions( [
	[	'TmpPrint',
		'gtk-print',
		'Print to Browser',
		'<Ctrl>P',
		'Print to browser',
		\&on_TmpPrint,
	],
] );

$app->{ui}->add_ui_from_string( q{
<ui>
	<menubar name='MenuBar'>
		<menu action='FileMenu'>
			<placeholder name='PrintActions'>
				<menuitem action='TmpPrint'/>
			</placeholder>
		</menu>
	</menubar>
</ui> } );

sub on_TmpPrint {
	warn "No real printing, tmp solution\n";
	my $tmpdir = File::Spec->tmpdir;

	# Export page to html
	my $file = "$tmpdir/zim-PrintToBrowser-$ENV{USER}.html";
	my $mask = umask 0077; # set umask to user only

	my $exporter = Zim::Store::Files->new(dir => $tmpdir);
	my $template = Zim::Formats->lookup_template('html', 'Print');
	return $app->error_dialog("Could not find template for PrintToBrowser")
		unless defined $template;
	$exporter->{_template} =  $template;
	my ($rep, $page) = @{$app}{'repository', 'page'};
	my $tmp = Zim::Page->new($exporter, $page->name);
	$tmp->set_source( Zim::File->new($file) );
	$tmp->set_format('html');
	$tmp->properties->{base} = $page->properties->{base};
	$tmp->clone($page, media => 'absolute');
	warn "Exported to $file\n";

	umask $mask; # reset old umask

	# Exec Browser
	my $uri = Zim::File->path2uri($file);
	$app->open_url($uri);
}
